import { Component, OnInit } from '@angular/core';
import {Picture} from "../../model/Picture";
import {PictureService} from "../../service/picture.service";
import {DialogService} from "primeng/api";
import {PictureeditComponent} from "../pictureedit/pictureedit.component";

@Component({
  selector: 'app-pictureadmin',
  templateUrl: './pictureadmin.component.html',
  styleUrls: ['./pictureadmin.component.css']
})
export class PictureadminComponent implements OnInit {

  pl:Array<Picture>
  constructor(private pictureservice:PictureService
    ,private dialogService: DialogService) {
    this.pl=new Array();

  }

  ngOnInit() {
    this.loadPictureList();

  }


  //从服务器端获取单页列表数据
  loadPictureList(){
    this.pictureservice.getPictureList()
      .then((data:any)=>{
        this.pl=new Array();
        this.pl=data;


      })


  }

  add(){
    //弹出编辑窗口
    const ref = this.dialogService.open(PictureeditComponent, {
      header: '添加图片'

    });

    //订阅窗口关闭事件

    ref.onClose.subscribe((picture: Picture) => {
      if (picture) {
        //保存数据到服务器
        this.pictureservice.savePicture(picture)
          .then((data:any)=>{
            if(data.msg=='ok'){
              this.loadPictureList();
            }
            else{
              //提示错误
            }


          })




      }
    });



  }

  //删除

  delete(id:string){

    this.pictureservice.deletePicture(id)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.loadPictureList();
        }
        else{
          //弹出错误信息;
        }


      })


  }

  update(id:string){
    //从服务器端读取数据
    this.pictureservice.getPictureById(id)
      .then((data:any)=>{
        if(data){
          let picture:Picture;
          picture=new Picture();
          picture=data;

          //发送要编辑的数据到编辑窗口
          //弹出编辑窗口
          const ref = this.dialogService.open(PictureeditComponent, {
            header: '修改图片',
            data:{
              "picture":picture
            }

          });

          //订阅窗口关闭事件

          ref.onClose.subscribe((picture: Picture) => {
            if (picture) {
              //保存数据到服务器
              this.pictureservice.savePicture(picture)
                .then((data:any)=>{
                  if(data.msg=='ok'){
                    this.loadPictureList();
                  }
                  else{
                    //提示错误
                  }


                })




            }
          });


        }


      });




  }



}

